package com.bnz.service.impl;

import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;



@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private RedisTemplate redisTemplate;

	//1. 查询所有学生
	@Override
	public List<Student> findAll() {
		//1.1 从redis中取出所有学生集合，
		BoundValueOperations boundValueOps = redisTemplate.boundValueOps("students");
		List<Student> students = (List<Student>) boundValueOps.get();
		//1.2 如果不存在，就从数据库中查询，并放到redis
		if(students == null || students.size() == 0){
			//1.2.1 从数据库中取得数据
			students = studentMapper.selectAll();
			//1.2.2 再将其放到redis中
			boundValueOps.set(students);
			System.out.println("正在从数据库中取数据。。。");

		}
		//1.3 返回
		return students;
	}

	//添加学生
	@Override
	public void add(Student stud) {
		//2.1 添加之前要清理缓存
		redisTemplate.delete("students");
		//2.2 再添加学生
		studentMapper.insert(stud);
	}

	//修改学生
	@Override
	public void update(Student student) {
		//3.1 清空缓存
		redisTemplate.delete("students");
		//3.2 添加到数据库中
		studentMapper.updateByPrimaryKey(student);
	}

	//根据id查询学生
	@Override
	public Student findBySid(int id) {
		return studentMapper.selectByPrimaryKey(id);
	}

	//根据id删除学生
	@Override
	public void delete(int id) {
		//5.1 清空缓存
		redisTemplate.delete("students");
		//5.2 从数据库中删除学生列表
		studentMapper.deleteByPrimaryKey(id);
	}
}
